var express = require('express');
var app = express();
var mysql = require('mysql');
const TUtils = require('./utils');

function queryDB(sql , parameters , onQuery){

    var res ={
        status:0 ,
        error:"",
        result:null
    }
    var opts={
        host:"tjiot.hhdata.cn",
        port:53306,
        user:"root",
        password:"hhuc1115",
        database:"dbdemo"
    };
    var connection = mysql.createConnection(opts);
    connection.connect(function (erConn) {
        if( erConn){
            res.status = -1;
            res.error="connect faild.";
            onQuery(res);
        }
        else{
            connection.query(sql, parameters ,function (erQuery , result) {
                if( erQuery){
                    res.status = -2;
                    res.error = "query faild.";
                    onQuery(res);
                }
                else{
                    res.status=1;
                    res.result = result;
                    onQuery(res);
                }
            })
        }
    });
}

var utils = new TUtils();

app.get("/acQuery/:ac", function(req,res){
    var ac = req.params.ac; 
})

app.get("/welcome", function (req,res) {
    res.send('welcome!');
});
app.get("/welcome/hello", function (req,res) {
    res.send('hello welcome!'+ JSON.stringify(req.query));
});
app.get("/queryUsers", function (req,res) {
    var sql ="select * from T_User where F_Code=?";
    var parameters =[req.query.code];
    queryDB(sql , parameters , function (queryResult) {
        res.send(JSON.stringify(queryResult));
    })
});
app.get("/checkLogin", function (req,res) {
    var sql ="select * from T_User where F_Code=? and F_Pwd=?";
    var parameters =[req.query.code , req.query.pwd];
    queryDB(sql , parameters , function (queryResult) {
        res.send(JSON.stringify(queryResult));
    })
});
app.get("/dbdemo/user/regist", function (req,res) {
    var sql ="insert INTO T_User( F_Code , F_NickName , F_Pwd , F_Desc) VALUES ( ? , ? ,'123' , ?)";
    var parameters =[req.query.code , req.query.nickName , req.desc];
    queryDB(sql , parameters , function (queryResult) {

        var insertId = queryResult.insertId? queryResult.insertId:0;
        sql ="select * from T_User where F_ID =?";
        queryDB(sql , [insertId], function (resQuery) {
            var resData ={
                query: queryResult ,
                data: resQuery
            }
            res.send(JSON.stringify(resData));
        })
    })
});

app.get("/db", function (req,res) {
    var parameters =JSON.stringify(req.query);
    res.send(parameters)
});

var server = app.listen(20030 , function () {
    console.log('start web server.')
})